#pragma once
#include <iostream>
#include <string>
#include "InertAddr.hpp"
#include <vector>
#include "Log.hpp"
using namespace LogModule;
class Route
{
private:
    std::vector<InertAddr> _online_user;
private:
    bool IsExist(InertAddr &peer)
    {
        for(auto &user:_online_user)
        {
            if(user==peer)
            return true;
        }
        return false;
    }
    bool AddUser(InertAddr &peer)
    {
        LOG(LogLevel::INFO)<<"新增一个在线用户："<<peer.StringAddr();
        _online_user.push_back(peer);
        return true;
    }
    void DeleteUser(InertAddr& peer)
    {
        for(auto iter=_online_user.begin();iter!=_online_user.end();iter++)
        {
            if(*iter==peer)
            {
                _online_user.erase(iter);
                break;
            }
        }
    }
public:
    void MessageRoute(int sockfd,const std::string &message,InertAddr& peer)
    {
        if(!IsExist(peer))
        {
            AddUser(peer);
        }
        //已经在线
        if(message=="QUIT")
        {
            DeleteUser(peer);    
        }

        std::string send_message =peer.StringAddr()+"#"+message;
        //TODO
        for(auto &user:_online_user)//转发给所有用户
        {
            sendto(sockfd, send_message.c_str(), send_message.size(), 0, (struct sockaddr *)&user.NerAddr(), sizeof(user.NerAddr()));
        }

    } 
    Route()
    {

    }
    ~Route()
    {
        
    }
};

